# -*- coding: utf-8 -*-
"""
Created on Mon Jul 15 20:07:45 2024

@author: JessicaNi
"""
import datetime

from openpyxl.reader.excel import load_workbook
from openpyxl.styles import Border, Side, Alignment, Font


# -*- coding: utf-8 -*-
"""
Created on Thu Jul 11 07:54:22 2024

@author: JessicaNi
"""

# 命令行输入格式 python transfer2ScheduleInorder.py 文件名
# 例如：python transferTf2Schedule.py 1.txt skiphead skiptail Bus V  new.xlsx 0or1
# 直接从非0变量到排好序的xlsx      0不按车号排序  1按车号排序


import sys
import csv
import pandas as pd

# 从命令行参数中获取文件名
file_name = sys.argv[1]
ignore_first = int(sys.argv[2])
ignore_last = int(sys.argv[3])
B = int(sys.argv[4])
V = int(sys.argv[5])
file_name2 = sys.argv[6]
S = int(sys.argv[7])


# # file_name = "./sol146.txt"
# file_name = "./BSP_6_136_sol.txt"
# file_name2 = "./sol146.xlsx"
# ignore_first = 1
# ignore_last = 1
# B = 6
# V = 136
# S = 1

def transferTime(tfTime):
    return str(tfTime // 60) + ":" + (str(tfTime % 60).zfill(2))


try:
    # 打开文件并读取内容
    with open(file_name, 'r') as file:
        content = file.read()
except FileNotFoundError:
    print("找不到文件:", file_name)
except Exception as e:
    print("发生错误:", e)

contents_array = content.split('\n')
contents_array = contents_array[ignore_first:-ignore_last]  # 去掉首尾无效的内容

cnt = 0

X = []
C = []
P = []
Q = []

# index = 车次
Y = {}
Yib = [-1 for i in range(V + 2)]
z1ib = [-1 for i in range(6)]
z0ib_H = [-1 for i in range(6)]
z1ib_H = [-1 for i in range(6)]
yib_H = [-1 for i in range(6)]
Tf = [-1 for i in range(V + 2)]
Tr = [-1 for i in range(V + 2)]
Tz = [0 for i in range(V + 2)]  # 注意-1处应该默认为0

idx_array = [-1 for i in range(len(contents_array))]
content_array = [-1 for i in range(len(contents_array))]
value_array = [-1 for i in range(len(contents_array))]
dic = {"x": 0, "y": 1, "c": 2, "p": 3, "q": 4, "tf": 5, "tr": 6, "tz": 7, "z0": 8, "z1": 9}
# 都是等于1的决策变量，后面的部分可以去掉
for i in range(len(contents_array)):
    content_array[i] = contents_array[i].split(" ")[0]
    value_array[i] = contents_array[i].split(" ")[-1]

    cnt += 1

# 对每个元素进行操作
cnt = 0
for i in range(len(content_array)):
    cnt += 1
    first_element = content_array[i][0:1]
    first2_element = content_array[i][0:2]
    if first_element in dic:
        idx_array[i] = dic[first_element]
    else:
        if first2_element in dic:
            idx_array[i] = dic[first2_element]
        else:
            pass

cnt = 0
for i in range(len(content_array)):
    cnt += 1
    # 处理Y
    if idx_array[i] == 1:
        ybi = content_array[i][1:].split(",")
        split_elements = [int(y) for y in ybi]
        y = split_elements[0]
        s = split_elements[1]
        Yib[s] = y
        yib_H[y] = s
        if y not in Y:
            Y[y] = []
            Y[y].append(s)
        else:
            Y[y].append(s)

    # 处理z1
    if idx_array[i] == 9:
        z1bi = content_array[i][1:].split(",")
        split_elements = [int(z1) for z1 in z1bi]
        b = split_elements[1]
        j = split_elements[2]
        i = split_elements[3]
        if j == 0:
            z1ib[b] = i
        z1ib_H[b] = i


    # 处理z0
    if idx_array[i] == 8:
        z0bi = content_array[i][1:].split(",")
        split_elements = [int(z0) for z0 in z0bi]
        b = split_elements[1]
        j = split_elements[2]
        i = split_elements[3]
        z0ib_H[b] = i


    # 处理tf
    if idx_array[i] == 5:
        tf = int(content_array[i][2:])
        tfTime = int(value_array[i].split(".")[0])
        Tf[tf] = tfTime
    # 处理tr
    if idx_array[i] == 6:
        tr = int(content_array[i][2:])
        trTime = int(value_array[i].split(".")[0])
        Tr[tr] = trTime
    # 处理tz
    if idx_array[i] == 7:
        tz = int(content_array[i][2:])
        tzTime = int(value_array[i].split(".")[0])
        Tz[tz] = tzTime
    # 处理q
    if idx_array[i] == 4:
        q = int(content_array[i][1:])

bus_use = len(Y)
print(f"当前解共使用了{bus_use}辆车。")
Result = []


usedB = {}
for i in range(1, V + 1, 2):

    if i in {z0ib_H[1] + 1, z0ib_H[3] + 1, z0ib_H[5] + 1, z1ib_H[1] + 1, z1ib_H[3] + 1, z1ib_H[5] + 1, yib_H[0] + 1, yib_H[2] + 1, yib_H[4] + 1}:
        flag = 1
        tmp = []
        ch = -1
        for j in {0,1,2,3,4,5}:
            if z0ib_H[j]+1 == i:
                ch = j
            elif z1ib_H[j]+1 == i:
                ch = j
            elif yib_H[j]+1 == i:
                ch = j
        tmp.append(ch)  # 车号
        tmp.append("  ")  # 车次
        tmp.append(transferTime(Tf[i-1]+Tr[i-1]))  # 出发
        tmp.append(26)  # 行驶时间
        tmp.append(transferTime(Tf[i-1] +Tr[i-1] + 26))  # 到达=出发+行驶

        tmp.append("三场")  # 主站停站时间

        tmp.append("  ")  # 主站停站时间

        tmp.append("  ")  # 车次
        tmp.append("  ")  # 出发
        tmp.append("  ")  # 行驶时间
        tmp.append("  ")  # 到达=出发+行驶

        tmp.append("  ")  # 副站停站时间

        tmp.append("  ")  # 发车间隔

        Result.append(tmp)

    if i == q+1:
        break

    tmp = []
    tmp.append(Yib[i])  # 车号
    tmp.append(str(i))  # 车次
    tmp.append(transferTime(Tf[i]))  # 出发
    tmp.append(Tr[i])  # 行驶时间
    tmp.append(transferTime(Tf[i] + Tr[i]))  # 到达=出发+行驶

    if Yib[i] not in usedB.keys():
        usedB[Yib[i]] = []
        usedB[Yib[i]].append(i)
        # tmp.append(0)  # 主站停站时间
        if Yib[i] in {1,3,5}:
            tmp.append("三，入入")  # 主站停站时间
        else:
            tmp.append("三")  # 主站停站时间
    else:
        if i in {z1ib[1], z1ib[3], z1ib[5]}:
            tmp.append("三，入入")  # 主站停站时间
        else:
            usedB[Yib[i]].append(i)
            tmp.append(Tz[i])  # 主站停站时间


    if i < 3:
        tmp.append(0)  # 发车间隔
    else:
        tmp.append(Tf[i] - Tf[i - 2])  # 发车间隔


    tmp.append(str(i + 1))  # 车次
    # tmp.append(Yib[i + 1])  # 车号
    tmp.append(transferTime(Tf[i + 1]))  # 出发
    tmp.append(Tr[i + 1])  # 行驶时间
    tmp.append(transferTime(Tf[i + 1] + Tr[i + 1]))  # 到达=出发+行驶

    tmp.append(Tz[i + 1])  # 副站停站时间

    if i < 3:
        tmp.append(0)  # 发车间隔
    else:
        tmp.append(Tf[i + 1] - Tf[i - 1])  # 发车间隔


    Result.append(tmp)

# 表头
header = ['班别', '下行车次', '大关小区', '下行单程时间', '下行到达时间', '下行停站时间', '下行发车间隔', "  ",
          '上行车次', '新安天苑南', '上行单程时间', '上行到达时间', '上行停站时间', '上行发车间隔']

Result2 = []
for j in range(0, 7):
    tmp = [Result[i][j] for i in range(len(Result))]
    Result2.append(tmp)

Result2.append([" " for i in range(len(Result))])
for j in range(7, 13):
    tmp = [Result[i][j] for i in range(len(Result))]
    Result2.append(tmp)

data = {}
cnt = 0
for key in header:
    data[key] = Result2[cnt]
    cnt += 1

print(data)

# 将数据字典转换为DataFrame
data = pd.DataFrame(data)
data['DepartureTime_sorted'] = pd.to_datetime(data['大关小区'], format='%H:%M').dt.strftime('%H%M').astype(int)
# 按照发车时间排序
data = data.sort_values(by='DepartureTime_sorted')

# 确定使用的车辆数
bus_use = []
first_column = data.iloc[:, 0]
length = len(first_column)
for i in range(length):
    if data.iloc[i, 0] not in bus_use:
        bus_use.append(data.iloc[i, 0])
print("使用的车辆数量为{}".format(len(bus_use)), bus_use)

data.drop('DepartureTime_sorted', axis=1, inplace=True)
# 将用到的车辆按序号排列(高峰车号将发生变化)
if S == 0:
    pass
if S == 1:
    for i in range(length):
        data.iloc[i, 0] = bus_use.index(data.iloc[i, 0]) + 1


# 打印表1统计信息：
# 打印7、班别类型:
print("7、班别类型:")
if S == 0:
    print("上下午班:"+"0,2,4")
    print("高峰班:"+"1,3,5")
if S == 1:
    Bus = [-1, -1, -1]
    j = 0
    for i in range(length):
        if data.iloc[i, 5] == "三":
            Bus[j] = data.iloc[i, 0]
            j = j+1
        else:
            pass
    print("上下午班:" + str(Bus[0]) + "," + str(Bus[1]) + "," + str(Bus[2]))
    print("高峰班:", end='')
    k = 0
    for i in range(1,7):
        if i in {int(Bus[0]),int(Bus[1]),int(Bus[2])}:
            pass
        else:
            if k == 2:
                print(i)
            else:
                print(i, end='')
                print(",", end='')
            k = k+1
# 打印10、平均车日行程
print("10、平均车日行程:")
print("总驶里程:"+str(q/2*(5+6.1)+(3+6)*(12.3+11)))
print("平均车日行程:"+str((q/2*(5+6.1)+(3+6)*(12.3+11))/6))
# 打印11、平均车班行程
print("11、平均车班行程:")
print("平均车班行程:"+str((q/2*(5+6.1)+(3+6)*(12.3+11))/9))
# 打印12、营业里程：
print("12、营业里程:")
print("平营业里程:"+str(q/2*(5+6.1)))
print("里程利用率:"+str((q/2*(5+6.1))/(q/2*(5+6.1)+(3+6)*(12.3+11))))
# 打印13、平均工作车时
print("13、平均工作车时:")
sumWorkTime = 0
for i in range(1, q+1, 1):
    sumWorkTime += Tr[i]
print("总工作车时："+str(sumWorkTime))
print("平均工作车时："+str(sumWorkTime/6))
# 打印14、平均车班工时
print("14、平均车班工时:")
print("总车班工时："+str(sumWorkTime+(3+6)*(30+26)))
print("平均车班车时："+str((sumWorkTime+(3+6)*(30+26))/9))

# 打印15、全日计划车次
print("15、全日计划车次:")
# 定义时间段（使用datetime.time表示时间段开始和结束时间）
time_slots = [
    ('00:00', '06:59'),
    ('07:00', '09:00'),
    ('09:01', '16:59'),
    ('17:00', '18:30'),
    ('18:31', '23:59')
]
# 转换时间段为datetime.time对象列表，方便比较
slots = [(datetime.datetime.strptime(start, '%H:%M').time(), datetime.datetime.strptime(end, '%H:%M').time()) for start, end in
         time_slots]
# 假设的车次发车时间列表，这里以字符串形式给出
departure_times_odd = []
departure_times_even = []
for i in range(1, q+1, 2):
    departure_times_odd.append(transferTime(Tf[i]))
for i in range(2, q+1, 2):
    departure_times_even.append(transferTime(Tf[i]))
# 转换发车时间为datetime.time对象
departure_times_dt_odd = [datetime.datetime.strptime(time, '%H:%M').time() for time in departure_times_odd]
departure_times_dt_even = [datetime.datetime.strptime(time, '%H:%M').time() for time in departure_times_even]
# 初始化计数器
count_per_slot_odd = [0] * len(slots)
count_per_slot_even = [0] * len(slots)
# 遍历每个发车时间，判断其属于哪个时间段
for dt in departure_times_dt_odd:
    for i, (start, end) in enumerate(slots):
        if start <= dt <= end:
            count_per_slot_odd[i] += 1
            break  # 找到一个匹配的时间段后跳出循环
for dt in departure_times_dt_even:
    for i, (start, end) in enumerate(slots):
        if start <= dt <= end:
            count_per_slot_even[i] += 1
            break  # 找到一个匹配的时间段后跳出循环
for i, (start, end) in enumerate(slots):
    print(f"时间段 {start.strftime('%H:%M')}-{end.strftime('%H:%M')} 的方向1车次数量为: {count_per_slot_odd[i]}")
    print(f"时间段 {start.strftime('%H:%M')}-{end.strftime('%H:%M')} 的方向2车次数量为: {count_per_slot_even[i]}")
# 打印17、平均发车间隔
print("17、平均发车间隔:")
# 日平峰
jg_r = 0
for i in range(2*(count_per_slot_odd[0]+count_per_slot_odd[1]+1)-1,2*(count_per_slot_odd[2]+count_per_slot_odd[1]+count_per_slot_odd[0]),2):
    jg_r += Tf[i] - Tf[i - 2]
for i in range(2*(count_per_slot_even[0]+count_per_slot_even[1]+1),2*(count_per_slot_odd[2]+count_per_slot_odd[1]+count_per_slot_odd[0])+1,2):
    jg_r += Tf[i] - Tf[i - 2]
print("日平峰平均发车间隔："+str(jg_r/(count_per_slot_odd[2]+count_per_slot_even[2])))
# 早晚平峰
jg_zwp = 0
for i in range(1,2*count_per_slot_odd[0],2):
    if i == 1:
        jg_zwp += 0
    else:
        jg_zwp += Tf[i] - Tf[i - 2]
for i in range(2,2*count_per_slot_even[0],2):
    if i == 2:
        jg_zwp += 0
    else:
        jg_zwp += Tf[i] - Tf[i - 2]
for i in range(2*(count_per_slot_odd[0]+count_per_slot_odd[1]+count_per_slot_odd[2]+count_per_slot_odd[3]+1)-1,q,2):
    jg_zwp += Tf[i] - Tf[i - 2]
for i in range(2*(count_per_slot_odd[0]+count_per_slot_odd[1]+count_per_slot_odd[2]+count_per_slot_odd[3]+1),q+1,2):
    jg_zwp += Tf[i] - Tf[i - 2]
print("早晚平峰平均发车间隔："+str(jg_zwp/(count_per_slot_odd[0]+count_per_slot_even[0]+count_per_slot_odd[4]+count_per_slot_even[4])))
# 早晚高峰
jg_zwg = 0
for i in range(2*(count_per_slot_odd[0]+1)-1,2*(count_per_slot_odd[1]+count_per_slot_odd[0]),2):
    jg_zwg += Tf[i] - Tf[i - 2]
for i in range(2*(count_per_slot_even[0]+1),2*(count_per_slot_odd[1]+count_per_slot_odd[0]),2):
    jg_zwg += Tf[i] - Tf[i - 2]
for i in range(2*(count_per_slot_odd[0]+count_per_slot_odd[1]+count_per_slot_odd[2]+1)-1,2*(count_per_slot_odd[3]+count_per_slot_odd[2]+count_per_slot_odd[1]+count_per_slot_odd[0]),2):
    jg_zwg += Tf[i] - Tf[i - 2]
for i in range(2*(count_per_slot_even[0]+count_per_slot_even[1]+count_per_slot_even[2]+1),2*(count_per_slot_odd[3]+count_per_slot_odd[2]+count_per_slot_odd[1]+count_per_slot_odd[0]),2):
    jg_zwg += Tf[i] - Tf[i - 2]
print("早晚高峰平均发车间隔："+str(jg_zwg/(count_per_slot_odd[1]+count_per_slot_even[1]+count_per_slot_odd[3]+count_per_slot_even[3])))



# 将修改后的输出的excel中
data.to_excel(file_name2, index=False)
# 加载工作簿并选择活动工作表
wb = load_workbook(file_name2)
ws = wb.active
# 创建边框样式
thin_border = Border(left=Side(style='thin'), right=Side(style='thin'), top=Side(style='thin'), bottom=Side(style='thin'))

# 将格式应用于所有单元格
for row in ws.iter_rows():
    for cell in row:
        cell.alignment = Alignment(horizontal='center', vertical='center')
        cell.border = thin_border
# 调整列宽
k = 0
width = [5, 9, 9, 14, 14, 14, 14, 5, 9, 12, 14, 14, 14, 14]
for col in ws.columns:
    max_length = 0
    column = col[0].column_letter # Get the column name
    ws.column_dimensions[column].width = width[k]
    k = k+1

for i in range(1, 4):  # 插入三行
    ws.insert_rows(1)  # 在第1行（即顶部）插入一行


# 添加第一行总表头（跨越多列）
ws.merge_cells('A1:N1')
ws['A1'] = '行 车 定 班 定 点 计 划（工作日）'
ws['A1'].font = Font(bold=True, size=20)  # 你可以根据需要调整字体大小
ws['A1'].alignment = Alignment(horizontal='center', vertical='center')
ws.merge_cells('A2:N2')
ws['A2'] = '表2、行  车  时  刻  表'
ws['A2'].font = Font(bold=True, size=16)  # 你可以根据需要调整字体大小
ws['A2'].alignment = Alignment(horizontal='center', vertical='center')
# 分表头
ws.merge_cells('A3:D3')
ws['A3'] = '98路'
ws['A3'].alignment = Alignment(horizontal='left', vertical='center')
ws.merge_cells('E3:G3')
ws['E3'] = '实行日期:'
ws['E3'].alignment = Alignment(horizontal='left', vertical='center')
ws.merge_cells('I3:K3')
ws['I3'] = '填表日期:' + datetime.date.today().strftime(' %Y-%m-%d')
ws['K3'].alignment = Alignment(horizontal='left', vertical='center')


# 保存格式化的工作簿
wb.save(file_name2)

print("Finish " + file_name2)
print("不同车辆执行的主站车次", usedB)

